package com.jltx.xq.coroutinesandrxpro

import android.annotation.SuppressLint
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.lifecycle.Observer
import com.jltx.xq.coroutinesandrxpro.bean.Resource
import com.jltx.xq.coroutinesandrxpro.ext.observeWithLifecycle
import com.jltx.xq.coroutinesandrxpro.ext.viewModels
import com.jltx.xq.coroutinesandrxpro.flow.MainViewModel5
import kotlinx.android.synthetic.main.activity_main5.*

class MainActivity5 : AppCompatActivity(), View.OnClickListener {
    private val mainViewModel5: MainViewModel5 by viewModels()


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main5)
        mainViewModel5.myUiLiveData.observe(this, Observer {
            updateResultTv(it)
        })

        observeWithLifecycle(mainViewModel5.myUiState) {
            updateResultTv(it)
        }
    }

    @SuppressLint("SetTextI18n")
    private fun updateResultTv(res: Resource<String>) {
        Log.d(TAG, "Thread ${Thread.currentThread()}")
        when {
            res.isLoading -> {
                result_tv.text = ""
            }
            res.isFail -> {
                result_tv.text = "fail exception: ${(res as Resource.Fail).error}"
            }
            res.valueOrNull == null -> {
                result_tv.text = "data is null"
            }
            else -> {
                result_tv.text = res.valueOrNull
            }
        }
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.cor_learn5_1 ->
                mainViewModel5.flowCreateRun()
            R.id.cor_learn5_2 ->
                mainViewModel5.flowOfCreateRun()
            R.id.cor_learn5_3 ->
                mainViewModel5.asFlowCreateRun()
            R.id.cor_learn5_4 ->
                mainViewModel5.channelFlowCreateRun()
        }
    }

    companion object {
        private const val TAG = "MainActivity5"
    }
}